import * as THREE from '../../build/three.module.js';
import {
  OrbitControls
} from '../../jsm/controls/OrbitControls.js';

const scene = new THREE.Scene();

/**
 * 通过 Three.js 提供的 CanvasTexture 类，可以将Canvas画布作为贴图使用
 */
// canvas 画布可以当做一张图片
const txr = new THREE.CanvasTexture(canvas);
console.log(txr.image);
const boxGeo = new THREE.BoxGeometry(200, 200, 200);
const boxMat = new THREE.MeshPhongMaterial({
  map: txr,
  side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(boxGeo, boxMat);
scene.add(mesh);

// 等待5秒后，修改 canvas 加载贴图图片，生成图案作为纹理贴图
setTimeout(() => {
  const img = new Image();
  img.src = '../../textures/square-outline-textured.png';
  img.onload = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.width);
    ctx.translate(-256, -64);
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    txr.image = canvas;
    txr.needsUpdate = true;
  };
}, 5000);

const al = new THREE.AmbientLight(0xffffff);
scene.add(al);
const k = innerWidth / innerHeight,
      s = 400,
      camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 10000);
camera.position.set(0, 0, 400);
camera.lookAt(scene.position);
const renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xaaaaaa);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
new OrbitControls(camera, renderer.domElement);

(function render() {
  renderer.render(scene, camera);
  requestAnimationFrame(render);
})();